package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private IEmployeeService  employeeService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password){
        try {
            //  获取主体对象
            Subject subject = SecurityUtils.getSubject();
            //  使用主体进行登录
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
            //  判断当前登录用户，状态是否为true
            Employee employee = (Employee) subject.getPrincipal();
            if (employee.isStatus()) {
                return new JsonResult(true, "登录成功");
            }
            throw new RuntimeException("账号已被禁用，请联系管理员");
        } catch (UnknownAccountException e) {
            return new JsonResult(false, "账号不存在");
        } catch (IncorrectCredentialsException e) {
            return new JsonResult(false, "密码错误");
        } catch (Exception e) {
            return new JsonResult(false, e.getMessage());

        }
    }

/*    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //  销毁当前session
        session.invalidate();
        //  重定向回到首页
        return "redirect:/login.html";
    }*/
}
